package cn.tramy.pinxian.common.util

import com.fasterxml.jackson.annotation.JsonProperty
import com.github.pagehelper.PageInfo
import java.util.*

/**
 * Created by yanjunhua on 2016/10/27.
 */
class CommonPageInfo(@get:JsonProperty
                     val queryUrl: String, val pageInfo: PageInfo<Any>) {

    @JsonProperty
    fun pageCount(): Int {
        return this.pageInfo.getPages()
    }

    @JsonProperty
    fun currentPageNum(): Int {
        return this.pageInfo.getPageNum()
    }

    //    public PageInfo getPageInfo()
    //    {
    //        return pageInfo;
    //    }

    @JsonProperty
    fun navigatePageUrls(): Map<String, String> {
        val result = TreeMap<String, String>()
        for (page in this.pageInfo.getNavigatepageNums()) {
            val pageUrl = buildPageUrl(page, this.pageInfo.getPageSize())
            result[page.toString()] = pageUrl
        }

        return result
    }

    @JsonProperty
    fun hasNextPage(): Boolean {
        return this.pageInfo.isHasNextPage()
    }

    @JsonProperty
    fun hasPrePage(): Boolean {
        return this.pageInfo.isHasPreviousPage()
    }

    @JsonProperty
    fun firstPageUrl(): String {
        return buildPageUrl(this.pageInfo.getFirstPage(), this.pageInfo.getPageSize())
    }

    @JsonProperty
    fun prePageUrl(): String {
        return if (this.hasPrePage()) buildPageUrl(this.pageInfo.getPrePage(), this.pageInfo.getPageSize()) else ""
    }

    @JsonProperty
    fun nextPageUrl(): String {
        val nextPage = this.pageInfo.getNextPage()
        val pageSize = this.pageInfo.getPageSize()
        return buildPageUrl(nextPage, pageSize)
    }

    @JsonProperty
    fun lastPageUrl(): String {
        return buildPageUrl(this.pageInfo.getLastPage(), this.pageInfo.getPageSize())
    }

    private fun buildPageUrl(pageNum: Int, pageSize: Int): String {
        var pageNum = pageNum
        var pageSize = pageSize
        val result = StringBuilder(this.queryUrl)
        if (pageNum <= 0) pageNum = 1
        if (pageSize > this.pageCount()) pageSize = this.pageCount()
        if (!result.toString().contains("?")) {
            result.append("?")
        }

        if (result.toString().contains("=")) {
            result.append("&")
        }

        result.append("$PARAMETER_PAGE_NO=$pageNum").append("&$PARAMETER_PAGE_SIZE=$pageSize")

        return result.toString()
    }

    companion object {
        val PARAMETER_PAGE_NO = "pageNo"
        val PARAMETER_PAGE_SIZE = "pageSize"
    }


}
